<template>
  <div style="background: #ffffff; margin-top: 24px">
    <a-button
      style="margin: 24px 0 24px 24px"
      type="primary"
      @click="handleAddFile"
      v-if="!prisoner"
      >新增文件</a-button
    >
    <a-card>
      <a-table
        :columns="columns"
        :row-key="(item) => item.id"
        :pagination="pagination"
        :data-source="dataSource"
        :loading="loading"
        @change="handleTableChange"
        bordered
      >
        <span slot="prisonerList" slot-scope="prisonerList">
          <a-tag
            v-for="prisoner in prisonerList"
            :key="prisoner.id"
            color="blue"
          >
            {{ prisoner.prisoner_name }}
          </a-tag>
        </span>
        <span slot="fileList" slot-scope="fileList">
          <a-tag v-for="file in fileList" :key="file.id" color="green">
            {{ file.file_type }}
          </a-tag>
        </span>
        <span slot="action" slot-scope="item">
          <a @click="handleLookFile(item)">查看</a>
          <template v-if="!prisoner">
            <a-divider type="vertical" />
            <a @click="handleDelFile(item)" >删除</a>
          </template>
        </span>
      </a-table>
    </a-card>

    <!-- 新增文件 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="文件名称"
        >
          <a-input
            v-decorator="[
              'article_name',
              { rules: [{ required: true, message: '请输入名称' }] },
            ]"
            placeholder="请输入名称"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="文件简述"
        >
          <a-input
            v-decorator="['article_content', { rules: [] }]"
            placeholder="请输入简述"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="面向人员"
        >
          <a-select
            mode="multiple"
            v-decorator="[
              'prisonerIdList',
              { rules: [{ required: true, message: '请输入面向人员' }] },
            ]"
            placeholder="请选择面向人员"
          >
            <a-select-option
              v-for="item in peopleList"
              :value="item.id"
              :key="item.id"
              >{{ item.prisoner_name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="有效日期"
        >
          <a-date-picker
            :format="`YYYY-MM-DD`"
            v-decorator="[
              'effective_date_end',
              { rules: [{ required: true, message: '请选择有效日期' }] },
            ]"
          />
          <!-- <a-range-picker :format="`YYYY-MM-DD`" v-decorator="['effective_date_end', { rules: [{ required: true, message: '请选择有效日期' }] }]" /> -->
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="备注"
        >
          <a-textarea
            v-decorator="['remark', { rules: [] }]"
            placeholder="请输入备注"
            :rows="4"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="点击上传"
        >
          <a-upload
            v-decorator="[
              'fileList',
              { rules: [{ required: true, message: '请先上传文件' }] },
            ]"
            name="file"
            :action="upload.action"
            :headers="upload.headers"
            :multiple="true"
            @change="handleFileChange"
          >
            <a-button><a-icon type="upload" /> 上传文件 </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";

const columns = [
  {
    title: "序号",
    customRender: (text, record, index) => `${index + 1}`,
    align: "center",
    width: 100,
  },
  {
    title: "面向人员",
    key: "prisonerList",
    dataIndex: "prisonerList",
    align: "center",
    width: 250,
    scopedSlots: { customRender: "prisonerList" },
  },
  {
    title: "文件名称",
    dataIndex: "article_name",
    align: "center",
  },
  {
    title: "内容简述",
    dataIndex: "article_content",
    align: "center",
  },
  {
    title: "文件类型",
    key: "fileList",
    dataIndex: "fileList",
    align: "center",
    scopedSlots: { customRender: "fileList" },
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
  },
  {
    title: "有效日期",
    dataIndex: "effective_date_end",
    key: "effective_date_end",
    align: "center",
    customRender: (date) => moment(date).format("YYYY-MM-DD HH:mm:ss"),
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    align: "center",
    width: 200,
  },
];

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

// import FileSaver from 'file-saver';
import { affairs } from "@/services";
import { BASE } from "@/services/api";

export default {
  name: "NoticeList",

  data() {
    return {
      columns: columns,
      dataSource: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      visible: false,
      formItemLayout,
      form: this.$form.createForm(this, { name: "add_file" }),
      upload: {
        action: `${BASE}/user/lookFile/upload`,
        headers: {
          token: localStorage.getItem("token"),
        },
      },
      fileList: [],
      confirmLoading: false,
      loading: false,
      type: 1,
      peopleList: [],
      prisoner: localStorage.getItem('admin.roles') === 0  //是否是被监管人员
    };
  },

  computed: {
    modalTitle() {
      return this.type === 1 ? "上传文件" : "修改文件";
    },
  },

  mounted() {
    this.getDataSource(this.pagination);
  },

  methods: {
    // 获取数据
    getDataSource({ current, pageSize }) {
      console.log({ current, pageSize });
      this.loading = true;
      affairs.getArticleList({ pageNo: current, pageSize }).then((res) => {
        if (res.data.code == 200) {
          this.dataSource = res.data.data.content;
          this.pagination.total = res.data.data.totalElements;
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },

    // 获取所有被监管人员
    getAllPrisoner() {
      affairs.getAllPrisoner().then((res) => {
        console.log(res);
        if (res.data.code === "200") {
          this.peopleList = res.data.data.items;
        }
      });
    },

    // 分页切换
    handleTableChange(pagination) {
      console.log(pagination);
      this.getDataSource(pagination);
    },

    // 新增文件
    handleAddFile() {
      this.type = 1;
      this.visible = true;
      this.getAllPrisoner();
    },

    // 文件上传列表
    handleFileChange({ file, fileList, event }) {
      console.log({ file, fileList, event });
      if (file.status === "done" && file.response.code === "200") {
        // this.fileIdList.push(file.response.data)
        this.fileList.push(file);
      }
      // this.fileList = fileList
    },

    // 新建/编辑确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log("Received values of form: ", values);
          const params = {
            ...values,
            // effective_date_end: values.effective_date_end.map(date => moment(date).format('YYYY-DD-MM')).join(',')
            effective_date_end: moment(values.effective_date_end).format(
              "YYYY-MM-DD HH:mm:ss"
            ),
            fileIdList: this.fileList.map((file) => file.response.data),
          };
          if (this.type === 1) {
            affairs
              .addArticle(params)
              .then((res) => {
                console.log(res);
                if (res.data.code === "200") {
                  this.visible = false;
                  this.form.resetFields();

                  this.$message.success("新增成功");
                  this.getDataSource(this.pagination);
                }
              })
              .catch((e) => {
                this.$message.fail(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 取消新建
    handleCancel() {
      this.visible = false;
      this.form.resetFields();
    },

    // 查看列表中的文件
    handleLookFile(item) {
      console.log(item);
      const { id, file_name, file_type } = item.fileList[0];
      console.log(`${BASE}/user/lookFile/download?fileId=${id}`);
      // const fileName = `${file_name}.${file_type}`;
      const elink = document.createElement("a");
      // elink.download = fileName;
      elink.target = "_blank";
      elink.href = BASE
        ? `${BASE}/user/lookFile/download?fileId=${id}`
        : `http://123.57.18.253:8087/user/lookFile/download?fileId=${id}`;
      elink.click();
      console.log(`${file_name}.${file_type}`);
      const formData = new FormData();
      formData.append("fileId", id);
      console.log(formData);
      // affairs.downloadArticle(formData).then(res => {
      //   console.log(res, res.data);
      //   const blob = new Blob([res.data], { type: 'application/octet-stream' });
      //   console.log(URL.createObjectURL(blob));
      //   const fileName = `${file_name}.${file_type}`
      //   const elink = document.createElement('a')
      //   elink.download = fileName
      //   elink.href = URL.createObjectURL(blob)
      //   elink.click()
      //   URL.revokeObjectURL(elink.href)
      // });
    },

    // 删除列表中的文件
    handleDelFile(item) {
      const that = this;
      this.$confirm({
        title: "确认删除该文件吗？",
        content: () => <div style="color:red;">删除后不可恢复！</div>,
        okText: "删除",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          console.log("OK");
          const { id } = item;
          console.log(id);
          affairs.delArticle({ articleId: id }).then((res) => {
            console.log(res);
            if (res.data.code === "200") {
              that.$message.success("删除成功");
              that.getDataSource(that.pagination);
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}
.fold {
  width: calc(100% - 216px);
  display: inline-block;
}
.operator {
  margin-bottom: 18px;
}
@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
</style>
